package com.chb.test.prizeDrawDemo_11;

import java.util.ArrayList;
import java.util.Random;
import java.util.StringJoiner;

public class PrizeDrawBox extends Thread{
    public PrizeDrawBox() {
    }

    public PrizeDrawBox(String name) {
        super(name);
    }
    ArrayList<Integer> prizeDrawList = new ArrayList<>();
    int count = 6; // 抽取的次数
    boolean flag = false; // 判读是否完成
    @Override
    public void run() {
      while (true) {
          synchronized (Draw.look) {
              if(flag) {
                  break;
              } else {
                  if(count == 0) {
                      flag = true;
                      StringJoiner str = new StringJoiner(",");
                      int maxNum = 0;
                      int sum = 0;
                      for (int i = 0; i < prizeDrawList.size(); i++) {
                          if(maxNum < prizeDrawList.get(i)) {
                              maxNum = prizeDrawList.get(i);
                          }
                          sum += prizeDrawList.get(i);
                          str.add(prizeDrawList.get(i) + "");
                      }
                      if(maxNum >= Draw.maxPrice) {
                          Draw.maxPrice = maxNum;
                          Draw.name = getName();
                          if(getName().equals("抽奖箱1")) {
                              Draw.box1 = true;
                          } else {
                              Draw.box2 = true;
                          }
                      }
                      String listStr = str.toString();
                      System.out.println("在此次抽奖过程中," + getName() + "总共产生了6个奖项");
                      System.out.println("分别为：" + listStr + "最高奖项为"+maxNum+"元，总计"+ sum +"元");
                      if(Draw.box1 && Draw.box2) {
                          System.out.println("最大奖项出现在："+Draw.name + "，金额为：" + Draw.maxPrice);
                      }
                      // 求出抽取的结果
                      break;
                  } else {
                      count --;
                      Random random = new Random();
                      int num = random.nextInt(Draw.drawList.length);
                      prizeDrawList.add(Draw.drawList[num]);
                  }
              }
          }
      }
    }
}
